package com.littlepay.kr4.paulin.dfeba77;

import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.MenuItem;
import android.widget.Toast;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.littlepay.kr4.paulin.dfeba77.adapter.LineChartAdapter;
import com.littlepay.kr4.paulin.dfeba77.adapter.PieChartAdapter;
import com.littlepay.kr4.paulin.dfeba77.entity.Sticker;
import com.littlepay.kr4.paulin.dfeba77.utils.DateUtil;

import java.util.ArrayList;
import java.util.List;

public class OverviewActivity extends AppCompatActivity implements OnChartValueSelectedListener {
    private LineChart lineChart;
    private PieChart pieChart;
    protected Typeface mTfRegular;
    protected Typeface mTfLight;
    protected Typeface tf;
    //private static ArrayList<Entry> yVals1;
    protected String[] mMonths = new String[] {
            "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
    };
    protected String[] mParties = new String[] {
            "基础", "娱乐", "购物", "其他"
    };
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overview);

        //Toast.makeText(this, DateUtil.getLastMonth(DateUtil.getTodayDate()),Toast.LENGTH_SHORT).show();
        //ToolBar
        toolbar = (Toolbar) findViewById(R.id.toolbar_overview);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null){
            //getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setTitle("消费近况");
        }

        lineChart = (LineChart) findViewById(R.id.line_chart);
        pieChart = (PieChart) findViewById(R.id.pie_chart);
        //字体相关设定
        mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");
        tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        /*lineChart相关项目*/
        // no description text
        lineChart.getDescription().setEnabled(false);
        // enable touch gestures
        lineChart.setTouchEnabled(false);
        //??
        lineChart.setDragDecelerationFrictionCoef(0.9f);
        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setDrawGridBackground(false);
        lineChart.setHighlightPerDragEnabled(true);
        //padding没有用
        //lineChart.setPadding(250,0,250,0);
        //lineChart.setPaddingRelative(250,0,250,0);
        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);
        // set an alternative background color
        lineChart.setBackgroundColor(Color.WHITE);
        //animation speed
        lineChart.animateX(1000);

        // get the legend (only possible after setting data)
        Legend legend = lineChart.getLegend();
//
//        // modify the legend ...
//        l.setForm(Legend.LegendForm.LINE);
//        l.setTypeface(mTfLight);
//        l.setTextSize(11f);
//        l.setTextColor(Color.BLACK);
//        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
//        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
//        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
//        l.setDrawInside(false);
        legend.setEnabled(false);

        XAxis xAxis = lineChart.getXAxis();
//        xAxis.setTypeface(mTfLight);
//        xAxis.setTextSize(11f);
//        xAxis.setTextColor(Color.BLACK);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        //TODO:设置x轴minmax的适配器
        //最小值是做左边数据-0.2f,但是这样会让数据下标对不齐x数据
        //最小值是当前月份-3，最大使当前月份+1

//        xAxis.setAxisMinimum(0);
//        xAxis.setAxisMaximum(6);
        //x轴数据默认在上方，需要设置到下方,而且要放在inside否则会被切断，着调x轴数据
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);
        xAxis.setTextSize(15f);
        xAxis.setDrawLimitLinesBehindData(false);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mMonths[(int) value % mMonths.length];
            }
        });
        //xAxis.setAvoidFirstLastClipping(true);
        new LineChartAdapter().setXAxis(lineChart);
        xAxis.setEnabled(true);

//        YAxis leftAxis = lineChart.getAxisLeft();
//        leftAxis.setTypeface(mTfLight);
//        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        //设置 Y上下限
        //TODO:设置上下限的适配器
//        leftAxis.setAxisMaximum(5000f);
//        leftAxis.setAxisMinimum(-2500f);
//        leftAxis.setDrawGridLines(true);
//        leftAxis.setGranularityEnabled(true);
//        leftAxis.setEnabled(false);

        YAxis rightAxis = lineChart.getAxisRight();
//        rightAxis.setTypeface(mTfLight);
//        rightAxis.setTextColor(Color.BLACK);
//        rightAxis.setAxisMaximum(5000);
//        rightAxis.setAxisMinimum(2000);
//        rightAxis.setDrawGridLines(false);
//        rightAxis.setDrawZeroLine(false);
//        rightAxis.setGranularityEnabled(false);
        rightAxis.setEnabled(false);

        // add data
        setLineChartData();





        /*pieChart相关配置*/

        pieChart = (PieChart) findViewById(R.id.pie_chart);
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(5, 10, 5, 5);

        pieChart.setDragDecelerationFrictionCoef(0.95f);
        pieChart.setCenterTextTypeface(Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"));
//        不设置饼图的中间文字
        //pieChart.setCenterText(generateCenterSpannableText());

        pieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);
        //
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.WHITE);

        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);

        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);

        pieChart.setDrawCenterText(true);

        pieChart.setRotationAngle(0);
        // enable rotation of the chart by touch, current disabled
               pieChart.setRotationEnabled(false);
        pieChart.setHighlightPerTapEnabled(false);

        // pieChart.setUnit(" €");
        // pieChart.setDrawUnitsInChart(true);

        // add a selection listener
        pieChart.setOnChartValueSelectedListener(this);

        setPieChartData();

        pieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // pieChart.spin(2000, 0, 360);

        Legend l = pieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(true);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }
    //获取并设置数据
    private void setLineChartData() {

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();

//        for (int i = 0; i < count; i++) {
//            float mult = range / 2f;
//            float val = (float) (Math.random() * mult) + 50;
//            yVals1.add(new Entry(i, val));
//        }
//        yVals1.add(new Entry(1,3806.71f));
//        yVals1.add(new Entry(2,1498.30f));
//        yVals1.add(new Entry(3,2003.29f));
//        yVals1.add(new Entry(4,1151.89f));
//        yVals1.add(new Entry(5,500f));
        //数据获取和添加
        LineChartAdapter lineChartAdapter = new LineChartAdapter();
        //获取每个月的消费
        List<Float> costList = lineChartAdapter.getAllMonthCost();
        //倒序添加，因为数据库取的时候是按照倒序日期获取
        int index = costList.size() - 1;
        for(int i = LineChartAdapter.getMinMonth();i <= LineChartAdapter.getCurrentMonth();i++){
            yVals1.add(new Entry(i,costList.get(index--)));
        }
        //设定表格高度
        lineChartAdapter.setYAxis(lineChart,costList);
//        ArrayList<Entry> yVals2 = new ArrayList<Entry>();
//
//        for (int i = 0; i < count-1; i++) {
//            float mult = range;
//            float val = (float) (Math.random() * mult) + 450;
//            yVals2.add(new Entry(i, val));
////            if(i == 10) {
////                yVals2.add(new Entry(i, val + 50));
////            }
//        }

//        ArrayList<Entry> yVals3 = new ArrayList<Entry>();
//
//        for (int i = 0; i < count; i++) {
//            float mult = range;
//            float val = (float) (Math.random() * mult) + 500;
//            yVals3.add(new Entry(i, val));
//        }

        LineDataSet set1;

        if (lineChart.getData() != null &&
                lineChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
/*            set2 = (LineDataSet) lineChart.getData().getDataSetByIndex(1);
            set3 = (LineDataSet) lineChart.getData().getDataSetByIndex(2);*/
            set1.setValues(yVals1);
/*            set2.setValues(yVals2);
            set3.setValues(yVals3);*/
            lineChart.getData().notifyDataChanged();
            lineChart.notifyDataSetChanged();
            //lineChart.notifyAll();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals1, "DataSet 1");

            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//            set1.setColor(ColorTemplate.getHoloBlue());
            set1.setColor(getResources().getColor(R.color.line_chart_base));
            set1.setCircleColor(getResources().getColor(R.color.line_chart_base));
            set1.setLineWidth(4f);
            set1.setCircleRadius(5f);
            set1.setFillAlpha(65);
            set1.setFillColor(ColorTemplate.getHoloBlue());
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);

            //set1.setFillFormatter(new MyFillFormatter(0f));
            //set1.setDrawHorizontalHighlightIndicator(false);
            //set1.setVisible(false);
            //set1.setCircleHoleColor(Color.WHITE);

            // create a dataset and give it a type
//            set2 = new LineDataSet(yVals2, "DataSet 2");
//            set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
//            set2.setColor(Color.RED);
//            set2.setCircleColor(Color.WHITE);
//            set2.setLineWidth(2f);
//            set2.setCircleRadius(3f);
//            set2.setFillAlpha(65);
//            set2.setFillColor(Color.RED);
//            set2.setDrawCircleHole(false);
//            set2.setHighLightColor(Color.rgb(244, 117, 117));
            //set2.setFillFormatter(new MyFillFormatter(900f));

//            set3 = new LineDataSet(yVals3, "DataSet 3");
//            set3.setAxisDependency(YAxis.AxisDependency.RIGHT);
//            set3.setColor(Color.YELLOW);
//            set3.setCircleColor(Color.WHITE);
//            set3.setLineWidth(2f);
//            set3.setCircleRadius(3f);
//            set3.setFillAlpha(65);
//            set3.setFillColor(ColorTemplate.colorWithAlpha(Color.YELLOW, 200));
//            set3.setDrawCircleHole(false);
//            set3.setHighLightColor(Color.rgb(244, 117, 117));

            // create a data object with the datasets
            //LineData data = new LineData(set1, set2, set3);
            LineData data = new LineData(set1);
            data.setValueTextColor(Color.GRAY);
            data.setValueTextSize(15f);
            // set data
            lineChart.setData(data);
            //lineChart.getXAxis().setAvoidFirstLastClipping(false);
        }
    }

    private void setPieChartData() {

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
//        for (int i = 0; i < count; i++) {
//            entries.add(new PieEntry((float) (Math.random() * mult) + mult / 5, mParties[i % mParties.length]));
//        }
        PieChartAdapter pieChartAdapter = new PieChartAdapter();
        List<Sticker> pieDate = pieChartAdapter.getCurrentMonthCostDetail();
        float[] pieEntry = new float[4];
        //pieEntry
        //分别是
        // 1.基础（吃饭 出行 住宿 医疗）
        // 2.娱乐
        // 3.购物
        // 4.其他
        for (int i = 0; i<pieDate.size(); i++){
            switch (pieDate.get(i).getAttribution()){
                //基础
                case 1:
                case 2:
                case 5:
                case 8:
                    pieEntry[0] += pieDate.get(i).getCost();
                    break;
                //娱乐
                case 4:
                    pieEntry[1] += pieDate.get(i).getCost();
                    break;
                //购物
                case 3:
                    pieEntry[2] += pieDate.get(i).getCost();
                    break;
                //其他
                default:
                    pieEntry[3] += pieDate.get(i).getCost();
                break;
            }
        }
        for(int i = 0; i < 4;i++){
            entries.add(new PieEntry(pieEntry[i], mParties[i % mParties.length]));
        }
        //PieDataSet dataSet = new PieDataSet(entries, "Election Results");
        PieDataSet dataSet = new PieDataSet(entries, "消费比例");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);


        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.GRAY);
        data.setValueTypeface(tf);
        pieChart.setEntryLabelColor(Color.GRAY);
        pieChart.setData(data);

        //重新绘制
        // undo all highlights
        pieChart.highlightValues(null);
        pieChart.invalidate();
    }

    private SpannableString generateCenterSpannableText() {
        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.5f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.65f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return false;
    }

}
